package com.rndemo.rn.view;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.common.build.ReactBuildConfig;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.uimanager.LayoutShadowNode;
import com.facebook.react.uimanager.ThemedReactContext;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import javax.annotation.Nullable;


/**
 * Created by tzj on 2018/4/9.
 * 这里加了选择图片
 */
@ReactModule(name = "RCTWebView")
public class ReactWebViewManager extends com.facebook.react.views.webview.ReactWebViewManager {
    private static final int CHOISE_PIC =3541;
    private static final int CHOISE_PIC_OLD =3542;
    private ValueCallback<Uri[]> fielCallback;
    private ValueCallback<Uri> oldFielCallback;
    private Uri photoUri;

    ActivityEventListener listener = new ActivityEventListener() {
        @Override
        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
            ReactWebViewManager.this.onActivityResult(requestCode,resultCode,data);
        }
        @Override
        public void onNewIntent(Intent intent) {
        }
    };

    @Override
    protected ReactWebView createReactWebViewInstance(final ThemedReactContext reactContext){
        ReactInstanceManager reactInstanceManager = ((ReactApplication) reactContext.getApplicationContext()).getReactNativeHost().getReactInstanceManager();
        reactInstanceManager.getCurrentReactContext().addActivityEventListener(listener);
        return super.createReactWebViewInstance(reactContext);
    }

    @Override
    public void onDropViewInstance(WebView webView) {
        ReactInstanceManager reactInstanceManager = ((ReactApplication) webView.getContext().getApplicationContext()).getReactNativeHost().getReactInstanceManager();
        if(reactInstanceManager.getCurrentReactContext()!=null){
            reactInstanceManager.getCurrentReactContext().removeActivityEventListener(listener);
        }
        super.onDropViewInstance(webView);
    }

    @Override
    public boolean canOverrideExistingModule() {
        return true;
    }

    @Override
    protected WebView createViewInstance(final ThemedReactContext reactContext) {
        WebView webView = super.createViewInstance(reactContext);
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onConsoleMessage(ConsoleMessage message) {
                if (ReactBuildConfig.DEBUG) {
                    return super.onConsoleMessage(message);
                }
                // Ignore console logs in non debug builds.
                return true;
            }
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                fielCallback = filePathCallback;
                reactContext.startActivityForResult(Intent.createChooser(fileChooser(null), "请选择"), CHOISE_PIC,null);
                return true;
            }
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooser(uploadMsg, null);
            }
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                openFileChooser( uploadMsg, acceptType,null);
            }
            public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType, String capture) {
                oldFielCallback = uploadMsg;
                reactContext.startActivityForResult(Intent.createChooser(fileChooser(acceptType), "请选择"), CHOISE_PIC_OLD,null);
            }
            public Intent fileChooser(String acceptType) {
                Intent intent = new Intent(Intent.ACTION_CHOOSER);
                Intent content = new Intent(Intent.ACTION_GET_CONTENT);
                content.addCategory(Intent.CATEGORY_OPENABLE);
                if (!TextUtils.isEmpty(acceptType)) {
                    content.setType(acceptType);
                } else {
                    content.setType("image/*");
                }
                intent.putExtra(Intent.EXTRA_INTENT, content);

                ArrayList<Intent> extraIntents = new ArrayList();
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                if(takePictureIntent.resolveActivity(reactContext.getPackageManager()) != null) {
                File externalpath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                File photoFile = new File(externalpath,String.valueOf(System.currentTimeMillis()) + ".jpg");
                if(photoFile != null) {
//                        String mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
//                        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri = Uri.fromFile(photoFile));
                }
//                    else {
//                        takePictureIntent = null;
//                    }
//                }
                extraIntents.add(takePictureIntent);
                intent.putExtra(Intent.EXTRA_INITIAL_INTENTS, (Parcelable[])extraIntents.toArray(new Intent[extraIntents.size()]));
                return intent;
            }
        });


        return webView;
    }


    private boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        if (CHOISE_PIC == requestCode){
            if (null != fielCallback){
                if (resultCode == Activity.RESULT_OK){
                    Uri result = photoUri;
                    if (data!=null){
                        result = data.getData();
                    }
                    fielCallback.onReceiveValue(new Uri[]{result});
                }else{
                    fielCallback.onReceiveValue(null);
                }
                fielCallback = null;
            }
            return true;
        }else if (CHOISE_PIC_OLD==requestCode){
            if (null != oldFielCallback){
                if (resultCode == Activity.RESULT_OK){
                    Uri result = photoUri;
                    if (data!=null){
                        result = data.getData();
                    }
                    oldFielCallback.onReceiveValue(result);
                }else{
                    oldFielCallback.onReceiveValue(null);
                }
                oldFielCallback = null;
            }
            return true;
        }else{
            return false;
        }
    }
    //请看这里 http://www.lrdcq.com/me/read.php/61.htm
    //========================================CSS
    @Override
    public LayoutShadowNode createShadowNodeInstance() {
        return super.createShadowNodeInstance();
    }
    @Override
    public Class<LayoutShadowNode> getShadowNodeClass() {
        return super.getShadowNodeClass();
    }
    @Override
    public void updateExtraData(WebView root, Object extraData) {
        super.updateExtraData(root, extraData);
    }
    //========================================注册常量(ReactTextInputManager)
    @Nullable
    @Override
    public Map<String, Object> getExportedViewConstants() {
        return super.getExportedViewConstants();
    }
    //========================================事件 (RefreshEvent) (一般Java 发送给js)
    @Override
    protected void addEventEmitters(ThemedReactContext reactContext, WebView view) {
        super.addEventEmitters(reactContext, view);
    }
    @Override
    public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
        return super.getExportedCustomDirectEventTypeConstants();
    }
    //========================================注册命令即方法（WebView）（一般js 发送给Java）
    @Nullable
    @Override
    public Map<String, Integer> getCommandsMap() {
        return super.getCommandsMap();
    }
    @Override
    public void receiveCommand(WebView root, int commandId, @Nullable ReadableArray args) {
        super.receiveCommand(root, commandId, args);
    }
}
